package learnjava.concur.chapter5;

public class P006 {
    public static void main(String[] args) {
        TwoPhaseTerminal tpt = new TwoPhaseTerminal();
        tpt.start();
        tpt.start();
    }
}

class TwoPhaseTerminal{

    private Thread monitorThread;

    private boolean stop = false; //可以不加volatile

    private boolean started = false;

    public synchronized void start(){
        synchronized (this){
            if(started) return;
            started = true;
            monitorThread = new Thread(()->{
                while (!stop){
                    try {
                        Thread.sleep(1000);
                        System.out.println("正在监控。。。");
                    }catch (Exception e){}
                }
                System.out.println("监控停止");
            });
            monitorThread.start();
        }
        //主线程通知monitor停止
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stop = true;
    }
}
